<?php
namespace Controllers;
use Config\Base as Config;
use DB\FacebookService;
use DB\UserService;

/**
 *
 * @author Evgeny Baranov <evgeny@baranov.eu>
 *
 */
class Login extends Base {

    /**
     *
     * @var string
     */
    protected $defaultAction = 'verify';

    /**
     *
     * @param array $param
     */
    function verify(array $param) {
        $fb = new FacebookService();

        $fb_user = $fb->getUser();
        $_SESSION['ozo']['after_login'] = isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : '/';
        if (!$fb_user) {
            $loginUrl = $fb->getLoginUrl(array('redirect_uri' => 'http://' . $_SERVER['HTTP_HOST'] . '/login/success'));
            header('Location: ' . $loginUrl);
        } else {
            header('Location: /login/success');
        }
        exit();
    }

    /**
     *
     * @param array $param
     */
    function success(array $param) {
        $us = new UserService();
        $fb = new FacebookService();

        $fb_user = $fb->getUser();
        $user = $us->findByProfileId($fb_user);

        if (!$user) {
            $profile = $fb->getProfile();
            $user = $profile->generateUserData();
            $user = $us->createUser($user);
            $profile->setUser($user);
            $us->createProfile($profile);
        }

        $_SESSION['user_id'] = $user->getId();
        $back = isset($_SESSION['ozo']['after_login']) && $_SESSION['ozo']['after_login'] ? $_SESSION['ozo']['after_login'] : '/';
        header('Location: ' . $back);
        exit();
    }

    function logout(array $param) {
        $fb = new FacebookService();
        $url = $fb->getLogoutUrl(array('next' => 'http://localozo.com/'));
        header('Location: ' . $url);
        session_destroy();
        exit();
    }
}